import isPromise from "../util/isPromise"
export const CALL_API = 'Call API'


export default store => next => action => {
    const callAPI = action[CALL_API];
    const { dispatch } = store;
    if (typeof callAPI === 'undefined') {
        return next(action)
    }
    if (!isPromise(callAPI)) {
        return next(action);
    }

    const getAction = data => {
        const finalAction = { ...action, ...data };
        delete finalAction[CALL_API]
        return finalAction
    }
    next(getAction({
        type: "AJAX_REQUEST_START"
    }))

    return callAPI.then(
        response => {
            dispatch(getAction({
                response,
                type: "AJAX_REQUEST_SUCCESS"
            }))
        },
        error => {
            dispatch(getAction({
                error: error.message || "error happened",
                type: "AJAX_REQUEST_FAIL"
            }))
        }
    ).catch(error => {
        dispatch(getAction({
            error: error.message || "error happen",
            type: "AJAX_REQUEST_FAIL"
        }))
    });
}
